package win.zxshuo.www.controller.pages;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import win.zxshuo.www.controller.exceptions.ResourceNotFoundException;
import win.zxshuo.www.model.CategoryModel;
import win.zxshuo.www.service.CategoryService;

import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;


    @RequestMapping("/{id}")
    public String categoryPage(@PathVariable Long id, Model model) throws Exception{


        Optional<CategoryModel> categoryModel = categoryService.getNameById(id);
        if (categoryModel.isPresent()){
            model.addAttribute("currentCategoryId",categoryModel.get().getId());
            model.addAttribute("title",categoryModel.get().getName());
        }else {
            throw new ResourceNotFoundException("404 分类目录未找到");
        }
        // 每个非章节页面都会需要获取的模型
        List<CategoryModel> categoryModels = categoryService.getAllCategories();
        model.addAttribute("categories",categoryModels);

        return "category";
    }

}
